package classpath

import (
	"os"
	"path/filepath"
)

/**
	类路径 结构体
 */
type Classpath struct {
	bootClasspath	Entry
	extClasspath	Entry
	userClasspath	Entry
}

/**
	解析结构体
 */
func Parse(cpOption string) *Classpath {
	cp := &Classpath{}
	cp.parseBootAndExtClasspath()
	cp.parseUserClasspath(cpOption)
	return cp
}

/**
	解析依赖类路径和扩展类路径
 */
func (self *Classpath) parseBootAndExtClasspath() {
	jreDir := getJreDir()
	jreLibPath := filepath.Join(jreDir, "lib", "*")
	self.bootClasspath = newWildcardEntry(jreLibPath)
	jreExtPath := filepath.Join(jreDir, "lib", "ext", "*")
	self.extClasspath = newWildcardEntry(jreExtPath)
}

/**
	解析用户指定类路径
*/
func (self *Classpath) parseUserClasspath(cpOption string) {
	if cpOption == "" {
		cpOption = "."
	}
	self.userClasspath = newEntry(cpOption)
}

/**
	获取jre环境
 */
func getJreDir() string {
	javaHome := "JAVA_HOME"
	if jh := os.Getenv(javaHome); jh != "" {
		return filepath.Join(jh, "jre")
	}
	panic("获取jre环境失败，请检查" + javaHome + "环境变量")
}


/**
	读取class内容
 */
func (self *Classpath) ReadClass(className string) ([]byte, Entry, error) {
	if data, entry, err := self.bootClasspath.readClass(className); err == nil {
		return data, entry, err
	}
	if data, entry, err := self.extClasspath.readClass(className); err == nil {
		return data, entry, err
	}
	return self.userClasspath.readClass(className)
}

/**
	获取用户类路径
 */
func (self *Classpath) String() string {
	return self.userClasspath.String()
}